<?php
class Members extends MY_SecuredController {

	function Members() {
		parent::MY_SecuredController();

		$this->requireRole('Admin');

		$this->load->helper(array('form','url'));
		$this->load->library('form_validation');
		$this->load->library('formdate');
	}

	public function index($clubid) {
		$this->_preRender(Current_User::user()->id);
		$this->_checkClubAdmin($clubid);

		$club = ClubModel::getClub($clubid);

		$this->_render_index($club, $data = array());
	}

	private function _checkClubAdmin($clubid) {
		if ($this->isOwner)
		  return true;

		$user = Current_User::user();
		$club = ClubModel::getClub($clubid);

		if (!$club->isAdmin($user->id)) {
			log_message('debug', 'User '.$user->id.' does not have permissions for club '.$clubid);

			$this->redirect('auth/denied', "You don't have enough permissions to access this option!", true);
		}
	}


    public function users($op, $clubid, $civlid = null) {
        $this->_preRender(Current_User::user()->id);
        $this->_checkClubAdmin($clubid);

        $club = ClubModel::getClub($clubid);
        if ($club === false) {
            $this->redirect('admin/clubs','Could not find club with ID '.$clubid, true);
            return;
        }

        $data['club'] = $club;

        try {
            if ($op == 'add') {
                $club->addPilot($this->input->post('user_id'));
            }
            else if ($op == 'delete') {
                $club->deletePilot($civlid);
            }
            else if ($op == 'search') {
                $results = PersonModel::locatePerson($this->input->post('user_term'));
                $options = array();
                $users = array();

                foreach ($club->Pilots as $ca) {
                    $users[] = $ca->id;
                }

                foreach ($results as $k => $a) {
                    if (!in_array($a['id'], $users)) {
                        $options[$a['id']] = $a['name'];
                    }
                }

                $data['user_search_results'] = $options;

                $this->_render_index($club, $data);
                return;
            }
        }
        catch (Exception $e) {
            $this->redirect('admin/members/index/'.$clubid, array(
                'message' => 'Ooops, the operation '.$op.' could not performed - try again later',
                'exception' => $e), true);
            return;
        }

        $this->redirect('admin/members/index/'.$clubid);
    }
    
    private function _render_index(&$club, &$data) {
        $data['club'] = $club;
        $data['people'] =  $club->findMembers();

        $this->render('admin/members/index', $data);
    }
}
?>